package com.zkt.club.gateway.filter;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.nacos.api.utils.StringUtils;
import lombok.SneakyThrows;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author 赵开泰
 * @program jc-club
 * @date 2025/3/23
 * @description 网关全局用户登录信息处理
 **/

@Component
public class LoginFilter implements GlobalFilter {
	
	@Override
	@SneakyThrows
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		ServerHttpRequest request = exchange.getRequest();
		
		ServerHttpRequest.Builder mutate = request.mutate();
		String url = request.getURI().getPath();
		
		if ("/auth/user/login".equals(url) || "/auth/user/register".equals(url)) {
			return chain.filter(exchange);
		}
		
		SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
		String loginId = String.valueOf(tokenInfo.getLoginId());
		
		if (StringUtils.isBlank(loginId)) {
			throw new Exception("未获取到用户信息");
		}
		
		mutate.header("loginId", loginId);
		
		return chain.filter(exchange.mutate().request(mutate.build()).build());
	}
	
}
